#!/bin/sh

op=$1

echo_help()
{
    echo "Usage: $0 {create|delete <source> <name> <user>}"
}

validate_source()
{
    a=$1
    if [ -z "$a" ];then
        echo_help
        exit 1
    fi

    if [ ! -e "/dev/$a" ];then
        echo "$a is not exists"
        exit 1
    fi
}

validate_name()
{
    a=$1
    if [ -z "$a" ];then
        echo_help
        exit 1
    fi
}

validate_user()
{
    a=$1
    if [ -z "$a" ];then
        echo_help
        exit 1
    fi

    id ${a} 2> /dev/null
    if [ "$?" != "0" ];then
        echo "system user: ${a} is not exists"
        exit 1
    fi
}

create()
{
    source=$1
    disk=$2
    user=$3
    if [ -z "$user" ];then
        user=grid
    fi
    group=`id -gn ${user}`
    if [ -z "$group" ];then
        group="asmadmin"
    fi

    chdev -l $source -a reserve_policy=no_reserve 2> /dev/null

    rendev -l $source -n ${disk} > /dev/null

    hdisk=/dev/r${disk}
    if [ ! -e "$hdisk" ];then
        echo "not found hdisk"
        exit 1
    fi

    chown ${user}:${group} $hdisk
    chmod 777 $hdisk
    echo ${disk}
}

delete()
{
    disk=$1

    rmdev -dl $disk
    rm -rf /dev/r${disk}
}

case ${op} in
create)
    disk=$2
    source=$3
    user=$4

    validate_name ${disk}
    validate_source ${source}
    validate_user ${user}

    create ${source} ${disk} ${user}
    ;;
delete)
    disk=$2

    validate_name ${disk}

    delete ${disk}
    ;;
*)
    echo_help
    exit 1
esac